package tech.aistar.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.Code.IdCardCheck;
import tech.aistar.Code.PhoneMessage;
import tech.aistar.entity.*;
import tech.aistar.service.IAgentService;
import tech.aistar.service.IMessageService;
import tech.aistar.service.IRegisterService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/Agent")
public class AgentController {
    @Autowired
    private IAgentService agentService;

    @Autowired
    private IRegisterService registerService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/info/{agentId}")
    public String select(HttpServletRequest request,@PathVariable("agentId") Integer agentId) {
//        String agentId = request.getParameter("agentId");
        Agent agent = agentService.selectById(Integer.valueOf(agentId));
        request.setAttribute("agent", agent);
        Register register = registerService.selectById(agent.getRegisterId());
        request.setAttribute("register", register);
        List<Message> messageStates = messageService.selectByState(register.getId());
        request.setAttribute("messageSize",messageStates.size());
        return "/personal_homepage/broker/infoB";
    }

    @PostMapping("/changepwd")
    public @ResponseBody
    Result updatepwd(Integer id, String password) {
        int count = registerService.updateById(id, password);

        if (count == 1) {
            return new Result("200", "修改成功", registerService.selectById(id));
        } else {
            return new Result("500", "修改失败");
        }
    }


//    @PostMapping("/changephone")
//    public @ResponseBody
//    Result updatephone(String phone, Integer id) {
//        int count = agentService.updatephoneById(phone, id);
//
//        if (count == 1) {
//            Result result = new Result("200", "修改成功", agentService.selectById(id));
//            return result;
//        } else {
//            Result result = new Result("500", "修改失败");
//            return result;
//        }
//    }
//
//
//    @PostMapping("/changename")
//    public @ResponseBody
//    Result updatename(String name, Integer id) {
//
//        int count = agentService.updateNameById(name, id);
//
//        if (count == 1) {
//            return new Result("200", "修改成功", agentService.selectById(id));
//        } else {
//            return new Result("500", "修改失败");
//        }
//    }
//
//
//    @PostMapping("/changegender")
//    public @ResponseBody
//    Result updategender(String gender, Integer id) {
//
//        int count = agentService.updategenderById(gender, id);
//
//        if (count == 1) {
//            return new Result("200", "修改成功", agentService.selectById(id));
//        } else {
//            return new Result("500", "修改失败");
//        }
//    }
//
//
//    @PostMapping("/insertIdentity")
//    public @ResponseBody
//    Result insertIdentity(String identity, Integer id){
//
//        int count = agentService.updateIdentityById(identity, id);
//
//        if(count==1){
//            return new Result("200","修改成功",agentService.selectById(id));
//        }else{
//            return new Result("500","修改失败");
//        }
//    }


    @PostMapping("/GetCode")
    public @ResponseBody Result getcode(HttpServletRequest request,String phone) {
//        final HttpSession httpSession=request.getSession();
//        httpSession.removeAttribute("checkCode");
//        httpSession.removeAttribute("checkPhone");
        redisTemplate.delete("checkCode2");
        redisTemplate.delete("checkPhone2");
        String checkCode = PhoneMessage.getPhonemsg(phone);
        if (checkCode != "true"){
            redisTemplate.opsForValue().set("checkCode2", checkCode, 5, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("checkPhone2", phone, 5, TimeUnit.MINUTES);
//            System.out.println(checkCode);
//            httpSession.setAttribute("checkCode",checkCode);
//            httpSession.setAttribute("checkPhone",phone);
//            final Timer timer=new Timer();
//            timer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    httpSession.removeAttribute("checkCode");
//                    httpSession.removeAttribute("checkPhone");
//                    System.out.println("checkCode删除成功");
//                    timer.cancel();
//                }
//            },1000*60*5);
            return new Result("200","获取成功");
        }else{
            return new Result("500","获取失败");
        }

    }


    @PostMapping("/changephone")
    public @ResponseBody
    Result updatephone(HttpServletRequest request,String phone, Integer id,String code) {
//        String checkCode = (String) request.getSession().getAttribute("checkCode");
//        String checkPhone = (String) request.getSession().getAttribute("checkPhone");
        String checkCode = (String) redisTemplate.opsForValue().get("checkCode2");
        String checkPhone = (String) redisTemplate.opsForValue().get("checkPhone2");
        if(code.equals(checkCode) && phone.equals(checkPhone)){
            int count = agentService.updatephoneById(phone, id);
//            request.getSession().removeAttribute("checkCode");
//            request.getSession().removeAttribute("checkPhone");
            redisTemplate.delete("checkCode2");
            redisTemplate.delete("checkPhone2");
            Result result = new Result("200", "修改成功",agentService.selectById(id));
            return result;
        }else{
            return new Result("500","验证码错误");
        }
    }


    @PostMapping("/insertIdentity")
    public @ResponseBody
    Result insertIdentity(String identity, Integer id,String name) {
        JSONObject jsonObject = IdCardCheck.IdCardCheck(name, identity);
        if ("true".equals(jsonObject.getString("isok"))) {
//            System.out.println(jsonObject.getJSONObject("IdCardInfor").getString("sex"));
            String gender = "";
            if ("男".equals(jsonObject.getJSONObject("IdCardInfor").getString("sex"))) {
                gender = "true";
            } else {
                gender = "false";
            }
            int count = agentService.updateIdentityById(identity, name, gender, id);
            if (count == 1) {
                return new Result("200", "认证成功", jsonObject.getJSONObject("IdCardInfor").getString("sex"));
            } else {
                return new Result("300", "认证失败");
            }
        } else {
            return new Result("500", "认证失败");
        }
    }

    @GetMapping("/Pic")
    public String Pic(HttpServletRequest request) {
        return "/personal_homepage/Pic";
    }


    @PostMapping("/lay")
    public @ResponseBody
    Result uploads(HttpServletRequest req, @RequestParam("file") MultipartFile file){
        //重新进行命名
        String fileName = UUID.randomUUID().toString()+"_"+file.getOriginalFilename();
//        String path = req.getServletContext().getRealPath("/img/");

        //构建File实例
        File f = new File("D:/nginx/html/img/"+fileName);

//        System.out.println(f);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        req.getSession().setAttribute("fileName",fileName);

        return new Result("200","文件上传成功!",fileName);
    }



    @PostMapping("/changepic")
    public @ResponseBody Result updatePic(HttpServletRequest req,Integer agentId) {
        String photograph = (String) req.getSession().getAttribute("fileName");
        req.getSession().removeAttribute("fileName");
        Agent agent = agentService.selectById(agentId);
        int count = agentService.updatephotographById(photograph,agentId);
        if (count==1){
            if (!agent.getPhotograph().equals("h2.png")){
                new File("D:/nginx/html/img/"+agent.getPhotograph()).delete();
            }
            return new Result("200","修改成功",photograph);
        }else{
            return new Result("500","修改失败");
        }
    }


    @PostMapping("/delpic")
    public @ResponseBody Result delPic(HttpServletRequest req,String photograph) {
        new File("D:/nginx/html/img/"+photograph).delete();
        return new Result("200","删除成功");
    }
}
